<template>
  <div :class="{ hidden }" class="pagination-container">
    <el-pagination
      :background="background"
      :current-page="currentPage"
      :page-size="pageSize"
      :layout="layout"
      :page-sizes="pageSizesRef"
      :total="total"
      v-bind="$attrs"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
  defineOptions({ name: 'Pagination' })
  import { ref, watch, computed } from 'vue'
  import { scrollTo } from '@/utils/scroll-to'
  interface Props {
    total: number
    page?: number
    limit?: number
    pageSizes?: number[]
    layout?: string
    background?: boolean
    autoScroll?: boolean
    hidden?: boolean
  }

  const props = withDefaults(defineProps<Props>(), {
    // size: 'default',
    page: 1,
    limit: 10,
    pageSizes: () => [10, 20, 30, 50, 100, 200],
    layout: 'total, sizes, prev, pager, next, jumper',
    background: true,
    autoScroll: true,
    hidden: false,
  })

  const emit = defineEmits<{
    (e: 'update:page', val: number): void
    (e: 'update:limit', val: number): void
    (e: 'pagination', payload: { page: number; limit: number }): void
  }>()

  const currentPage = computed({
    get: () => {
      return props.page
    },
    set: (val) => {
      emit('update:page', val)
    },
  })

  const pageSize = computed({
    get: () => {
      return props.limit
    },
    set: (val) => {
      emit('update:limit', val)
    },
  })

  // 处理 pageSizes：确保包含当前 pageSize
  const pageSizesRef = ref<number[]>([])
  watch(
    () => props.pageSizes,
    () => {
      const sizes = [...props.pageSizes]
      if (!sizes.includes(pageSize.value)) {
        sizes.unshift(pageSize.value)
      }
      pageSizesRef.value = sizes
    },
    { immediate: true },
  )
  // 分页大小发生改变
  function handleSizeChange(val: number) {
    console.log('handleSizeChange', val)
    pageSize.value = val
    emit('pagination', { page: currentPage.value, limit: val })
    if (props.autoScroll) {
      scrollTo(0, 800)
    }
  }
  // 当前页码发生改变
  function handleCurrentChange(val: number) {
    currentPage.value = val
    emit('pagination', { page: val, limit: pageSize.value })
    if (props.autoScroll) {
      scrollTo(0, 800)
    }
  }
</script>

<style scoped>
  .pagination-container {
    padding: 32px 16px;
  }
  .pagination-container.hidden {
    display: none;
  }
</style>
